package app.keter.portal.security.auth;

import app.keter.portal.security.CurrentUser;
import app.keter.portal.security.SecurityService;
import app.keter.portal.security.core.UserDetailsImpl;
import com.keter.framework.web.result.JSONResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service
public class AuthService {

  private static final Logger logger = LoggerFactory.getLogger(AuthService.class);
  @Autowired private AuthenticationManager authenticationManager;
  @Autowired private SecurityService security;


  public String login(String username, String password) {
    UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(username, password);
    final Authentication authentication = authenticationManager.authenticate(upToken);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    CurrentUser.setCurrentUser((UserDetailsImpl) authentication.getPrincipal());
//    SecurityService.setCurrentUser((UserDetailsImpl) authentication.getPrincipal());
    logger.debug("Current User Roles:{}",CurrentUser.getCurrentUser().getAuthorities());
//    return security.toToken(SecurityService.getCurrentUser());
    return security.toToken(CurrentUser.getCurrentUser());
  }

  public JSONResult refresh(String token) {
    return security.refresh(token);
  }

//  public JSONRessult refreshResponse(String token) {
//    return security.refreshResponse(token);
//  }
}
